import { ref } from 'vue'
import { restHelperInstance } from '@/composables/useGeoHelper'
import type { ILayer } from 'geoserver-helper/interface'

const layerList = ref<ILayer.ResLayerListItem[]>([])

const sortLayerList = ref<Record<string, ILayer.ResLayerListItem[]>>({})
export default function useLayersModal() {
    /**
     * @description: 获取图层列表
     * @param {Boolen} refreshData 是否更新数据（使用实时数据）
     * @return {Promise}
     */
    function getLayerList(refreshData = false, workspace?: string): Promise<ILayer.ResLayerListItem[]> {
        if (
            refreshData ||
            (!workspace && layerList.value.length === 0) ||
            (workspace && (!sortLayerList.value[workspace] || sortLayerList.value[workspace]!.length === 0) )
        ) {
            return new Promise((resove, reject) => {
              restHelperInstance.getLayerListApi(workspace)
                    .then(res => {
                        if (res.layers) {
                            if (res.layers && res.layers.layer && res.layers.layer.length > 0) {
                                if (workspace) {
                                    sortLayerList.value[workspace] = res.layers.layer
                                } else {
                                    layerList.value = res.layers.layer
                                }
                                resove(res.layers.layer)
                            } else {
                                resove([])
                            }
                        } else {
                            resove([])
                        }
                    })
                    .catch(() => {
                        reject(false)
                    })
            })
        } else {
            if (!workspace) {
                return Promise.resolve(layerList.value)
            } else {
                return Promise.resolve(sortLayerList.value[workspace] as ILayer.ResLayerListItem[])
            }
        }
    }
    return { layerList, sortLayerList, getLayerList }
}
